<?php

namespace App\Http\Controllers\Config;

use App\Models\Config\RoomPaytype;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class RoomPaytypeController extends Controller
{
    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
    }
    
    public function index(Request $request)
    {
        if ($request->ajax()) {

            $roompaytype= RoomPaytype::get();

            $records= $roompaytype->count();
            $page = $request->get("page");
            $pagerows = $request->get("rows");
            $total = intval(ceil($records / $pagerows));

            $roompaytype = $this->filters($request, $roompaytype);

            $roompaytype = $roompaytype->forPage($request->get("page"),$request->get("rows"));

            $rows = [];
            foreach ($roompaytype as $type){
                $rows[] = $type;
            }

            $data = [
                'rows' => $rows,
                'total'=> $total,
                'page' => $page,
                'records' => $records,
            ];

            return response()->json($data);

        } else {
            return view('/config/room_paytype/index');
        }
        
    }

    public function edit(Request $request)
    {
        $oper = $request->get('oper');

        if ($oper == "add"){
            $this->validate($request, [
                "value" => "required|int",
                "name" => "required",
            ]);

            $value = $request->get("value");
            $name = $request->get('name');
            $des = $request->get('des');
            
            $alltype = RoomPaytype::get();

            foreach ($alltype as $type){
                if ($type['value'] == $value){
                    return response()->json(["success" => false , "message" => "支付类型已存在"]);
                }
            }

            $roompaytype = new RoomPaytype();
            $roompaytype->value = intval($value);
            $roompaytype->name = $name; 
            $roompaytype->des = $des;
            $roompaytype->save();

        }elseif ($oper == "edit"){

            $this->validate($request, [
                "value" => "required|int",
                "name" => "required",
            ]);

            $id = $request->get('id');

            $roompaytype = RoomPaytype::find($id);

            $name = $request->get('name');
            $des = $request->get('des');

            $roompaytype->name = $name;
            $roompaytype->des = $des;
            $roompaytype->save();

        }elseif($oper == "del"){
            $this->validate($request, [
                "id" => "required"
            ]);
            $id = $request->get('id');

            $roompaytype = RoomPaytype::find($id);

            $roompaytype->delete();
        }

        return response()->json(["success" => true]);

    }
    
 
}
